import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/request/facility_request.dart';

// ignore: import_of_legacy_library_into_null_safe
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:photo_view/photo_view.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class PhotoViewPage extends StatefulWidget {
  final List<String>? data;
  final int index;

  PhotoViewPage({this.data, this.index = 0});

  static Future showPhoto(BuildContext context, {@required List<String>? dataSource, int index = 0}) async {
    final future = showDialog(
        context: context,
        useSafeArea: false,
        builder: (ctx) {
          return PhotoViewPage(data: dataSource, index: index);
        });
    return future;
  }

  @override
  _PhotoViewPageState createState() => _PhotoViewPageState();
}

class _PhotoViewPageState extends State<PhotoViewPage> {
  int index = 0;
  List<GlobalKey> globalkeys = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
    if (widget.data != null)
      for (int i = 0; i < widget.data!.length; i++) {
        globalkeys.add(GlobalKey());
      }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      backgroundColor: Colors.black,
      body: Stack(
        children: [
          Positioned.fill(
            child: buildContent(),
          ),
          Positioned(
            left: 0,
            right: 0,
            top: SizeFill.statusHeight! + 20,
            child: Container(
              alignment: Alignment.center,
              child: Container(
                height: SizeFill.setRx(24),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  color: MyColors.back_h,
                ),
//                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(
                  horizontal: 12,
                ),
                child: Text(
                  "${index + 1}/${widget.data!.length}",
                  style: TextStyle(
                    color: MyColors.color_255_255_255,
                    fontSize: MyFont.font16,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget buildContent() {
    if (widget.data == null) return Container();
    return Container(
      width: double.infinity,
      height: double.infinity,
      child: Swiper(
        index: index,
        itemCount: widget.data!.length,
        itemBuilder: (ctx, index) {
          return GestureDetector(
            child: buildItem(index),
            onLongPress: () {
              print('dddddd');
              ShowBottomSheet.showSheet(context, actions: ['保存到相册'], cancleString: '取消').then((value) {
                if (value == 1) {
                  _capturePng(context, index);
                }
              });
            },
          );
        },
        onIndexChanged: (index) {
          this.index = index;
          setState(() {});
        },
        onTap: (int index) {
          Navigator.pop(context);
        },
        autoplay: false,
      ),
    );
  }

  Widget buildItem(int index) {
    print(index);
    if (index == widget.data!.length - 1) {
      String url =
          "${Configuration.h5Share}${FacilityRequest.encodeBase64(UserCacheUil.getString(Configuration.mobile) ?? '')}";
      return Container(
        color: Colors.black,
        alignment: Alignment.center,
        child: RepaintBoundary(
          key: globalkeys[index],
          child: QrImage(
            data: url,
            size: SizeFill.screenWidth,
            embeddedImage: AssetImage('assets/images/icon_logo_2.png'),
            padding: EdgeInsets.all(20),
            backgroundColor: Colors.white,
          ),
        ),
      );
    }
    return Container(
      width: double.infinity,
      height: double.infinity,
      child: RepaintBoundary(
        key: globalkeys[index],
        child: PhotoView(
          loadingBuilder: (ctx, e) {
            return ProgressDialog.showFirstLoading();
          },
          imageProvider: NetworkImage(
            widget.data![index],
          ),
        ),
      ),
    );
  }

  void _capturePng(BuildContext context, int index) async {
    //检查是否有存储权限

    BuildContext? buildContext1 = globalkeys[index].currentContext;
    if (buildContext1 != null) {
      RenderRepaintBoundary? boundary = buildContext1.findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();
      savePhoto(pngBytes);
    }
  }

  void savePhoto(Uint8List pngBytes) async {
    var status = await Permission.storage.status;
    print('11111');

    if (!status.isGranted) {
      status = await Permission.storage.request();
    }
    print('22222');

    if (!status.isGranted) {
      // status = await Permission.storage.request();
      ShowToastWidget.showToast(msg: "请开启访问相册权限");
//这里需要开启权限
      return;
    }
    if (pngBytes == null) {
      ShowToastWidget.showToast(msg: '保存失败');
      return;
    }

    final result = await ImageGallerySaver.saveImage(pngBytes);

    ShowToastWidget.showToast(msg: '保存成功');
  }
}
